#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/6/22 14:47
# @Author : wn 
# @File: env.py
# @SoftWare: PyCharm
# @Site:
# @Table:
# ｡◕‿◕｡｡◕‿◕｡｡◕‿◕｡

import json
from operator import itemgetter

from django.db.models import Max
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.views import View

from trade.model_choices import *
from trade.models import *
from utils.chardate import chardate
from utils.service import my_page
from trade.search_page import search_enviro


class Enviro(View):
    '''
    环境管理
    '''

    def __init__(self):
        self.url = '/trade/enviro/'

    def get(self, request):
        # 当前访问用户
        customerid = request.GET.get('customerid', None)
        if customerid:
            request.session['customerid'] = customerid
            print('get方式，当前访问的用户是：', customerid)
        off = request.GET.get('offset', None)
        lim = request.GET.get('limit', None)

        # get请求修改环境
        get_envid_modify = request.GET.get('envid_modify', None)
        if lim is None and get_envid_modify is not None:
            # 策略表
            env_list = list(Environment.objects.using('quantWebDB').filter(envid=int(get_envid_modify)))  # [StragegyObj,]
            for item in env_list:
                result_dict = {}
                result_dict['envid'] = item.envid  # str
                result_dict['envname'] = item.envname
                result_dict['ip'] = item.ip
                result_dict['type'] = item.type
                result_dict['remark'] = item.remark
                result_dict['runpath'] = item.runpath
                result_dict['backtype'] = item.backtype
            result = my_page([result_dict], lim, off)
            return JsonResponse(result, safe=False)

        if off is None:
            return render(request, 'enviro_trade.html', {'url': self.url})
        else:
            result_list = []
            # 环境表
            enviro_list = list(Environment.objects.using('quantWebDB').all())
            for item in enviro_list:
                result_dict = {}
                result_dict['envid'] = item.envid
                result_dict['envname'] = item.envname
                result_dict['ip'] = item.ip
                result_dict['updatetime'] = item.updatetime
                result_dict['type'] = EnvType.get(item.type, None)
                result_dict['backtype'] = BackType.get(item.backtype, None)
                result_dict['runpath'] = item.runpath
                result_dict['remark'] = item.remark

                # 操作
                result_dict['eoption'] = item.envid
                result_list.append(result_dict)
            # 排序
            for item in result_list:
                if (item.get('envid') is None):
                    item['envid'] = '-1'
            result_list_sorted = sorted(result_list, key=itemgetter('envid'), reverse=True)
            result = my_page(result_list_sorted, lim, off)
            return JsonResponse(result, safe=False)

    def post(self, request):
        if request.POST.get('delete_enviro', None):
            envid = request.POST.get('id')
            # 仿真审批中是否有envid
            paobj = Paperapproval.objects.using('quantWebDB').filter(envid=envid)
            # 实盘审批中是否有envid
            laobj = Liveapproval.objects.using('quantWebDB').filter(envid=envid)
            if len(paobj)!=0 or len(laobj)!=0:
                # paperapproval中正在使用envid，不能删除envid
                return HttpResponse('h')
            elif request.POST.get("delete_enviro") == "1":
                # 没有策略在使用envid，可以删除
                return HttpResponse("f")
            elif request.POST.get("delete_enviro") == "2":
                try:
                    # 没有策略在使用envid，可以删除，真正删除
                    Environment.objects.using('quantWebDB').filter(envid=int(envid)).delete()
                    jsonRes = search_enviro(envname='', ip='', type='')
                    return jsonRes
                except Exception as e:
                    print(e)
                    return HttpResponse("")
        elif request.POST.get('enviro_search', None):
            # 前端查询条件
            data = json.loads(request.POST.get("data"))
            envname = data.get("envname", None)  # if no condition value is str ''
            envip = data.get("envip", None)  # if no condition value is str ''
            envtype = data.get("envtype", None)  # if no condition value is str ''
            jsonRes = search_enviro(envname=envname, ip=envip, type=envtype)
            return jsonRes
        else:
            data = request.POST
            envid_agg = Environment.objects.using('quantWebDB').all().aggregate(Max('envid'))
            # 数据表里是空时Max==None
            if envid_agg['envid__max'] == None:
                envid_agg['envid__max'] = 0
            envid_int = envid_agg['envid__max'] + 1
            envid_modify = json.loads(data['envid'])[0]
            if envid_modify=='':
                envid_modify = -1
            # 修改
            if Environment.objects.using('quantWebDB').filter(envid=int(envid_modify)).exists():
                '''
                判断envname，ip是否唯一
                此处是修改请求，做判断读数据库的时候应该按envid把当前记录去除掉在进行接下来的操作(liu20201012)
                '''
                if Environment.objects.using('quantWebDB').exclude(envid=int(envid_modify)).filter(envname=json.loads(data['envname'])[0]).exists():
                    return HttpResponse('eh')
                if Environment.objects.using('quantWebDB').exclude(envid=int(envid_modify)).filter(ip=json.loads(data['ip'])[0], type=json.loads(data['type'])[0],
                                              backtype=json.loads(data['backtype'])[0]).exists():
                    return HttpResponse('iph')
                Environment.objects.using('quantWebDB').filter(envid=int(envid_modify)).update(
                    envname=json.loads(data['envname'])[0],
                    ip=json.loads(data['ip'])[0],
                    type=json.loads(data['type'])[0],
                    remark=json.loads(data['remark'])[0],
                    updatetime=chardate(),
                    runpath=json.loads(data['runpath'])[0],
                    backtype=json.loads(data['backtype'])[0],
                )
            # 添加
            else:
                # 判断envname，ip是否唯一
                if Environment.objects.using('quantWebDB').filter(envname=json.loads(data['envname'])[0]).exists():
                    return HttpResponse('eh')
                if Environment.objects.using('quantWebDB').filter(ip=json.loads(data['ip'])[0], type=json.loads(data['type'])[0],
                                                                  backtype=json.loads(data['backtype'])[0]).exists():
                    return HttpResponse('iph')
                Environment.objects.using('quantWebDB').create(
                    envid=envid_int,
                    envname=json.loads(data['envname'])[0],
                    ip=json.loads(data['ip'])[0],
                    type=json.loads(data['type'])[0],
                    remark=json.loads(data['remark'])[0],
                    updatetime=chardate(),
                    runpath=json.loads(data['runpath'])[0],
                    backtype=json.loads(data['backtype'])[0],
                )
            jsonRes = search_enviro(envname='', ip='', type='')
            return jsonRes
